import React, { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Cell, Button, Avatar, Toast } from '@nutui/nutui-react-taro';
import { IconFont } from '@nutui/icons-react-taro';
import { getCurrentUser, logout } from '../../services/user';
import './index.scss';

const Profile: React.FC = () => {
  const [userInfo, setUserInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  useEffect(() => {
    fetchUserInfo();
  }, []);

  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      // 先尝试从本地获取用户信息
      const cachedUserInfo = Taro.getStorageSync('userInfo');
      
      if (cachedUserInfo) {
        setUserInfo(cachedUserInfo);
      } else {
        // 如果本地没有，则从服务器获取
        const token = Taro.getStorageSync('token');
        
        if (!token) {
          Taro.redirectTo({ url: '/pages/login/index' });
          return;
        }
        
        const response = await getCurrentUser();
        setUserInfo(response);
        Taro.setStorageSync('userInfo', response);
      }
    } catch (error) {
      setToastMessage(error.message || '获取用户信息失败');
      setShowToast(true);
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    Taro.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          logout();
        }
      }
    });
  };

  const handleEditProfile = () => {
    Taro.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  };

  if (loading) {
    return (
      <View className="profile-loading">
        <Text>加载中...</Text>
      </View>
    );
  }

  if (!userInfo) {
    return (
      <View className="profile-error">
        <Text>获取用户信息失败</Text>
        <Button 
          type="primary"
          onClick={() => Taro.redirectTo({ url: '/pages/login/index' })}
          className="login-button"
        >
          去登录
        </Button>
      </View>
    );
  }

  return (
    <View className="profile-container">
      <View className="profile-header">
        <View className="profile-info">
          <Avatar 
            size="large" 
            src={userInfo.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'} 
            className="profile-avatar"
          />
          <View className="profile-name-info">
            <Text className="profile-nickname">{userInfo.nickname}</Text>
            <Text className="profile-username">@{userInfo.username}</Text>
          </View>
        </View>
        
        <View className="profile-bio">
          {userInfo.bio || '这个人很懒，什么都没有留下'}
        </View>
        
        <Button 
          size="small" 
          className="edit-profile-btn"
          onClick={handleEditProfile}
        >
          编辑资料
        </Button>
      </View>
      
      <View className="profile-content">
        <Cell.Group title="账号设置">
          <Cell 
            title="我的收藏" 
            extra=""
            onClick={() => {
              Taro.showToast({
                title: '功能开发中',
                icon: 'none'
              });
            }}
          >
            <IconFont name="star" />
          </Cell>
          <Cell 
            title="我的点赞" 
            extra=""
            onClick={() => {
              Taro.showToast({
                title: '功能开发中',
                icon: 'none'
              });
            }}
          >
            <IconFont name="heart" />
          </Cell>
          <Cell 
            title="消息通知" 
            extra=""
            onClick={() => {
              Taro.showToast({
                title: '功能开发中',
                icon: 'none'
              });
            }}
          >
            <IconFont name="notice" />
          </Cell>
        </Cell.Group>
        
        <Cell.Group title="其他设置">
          <Cell 
            title="关于我们" 
            extra=""
            onClick={() => {
              Taro.showToast({
                title: '功能开发中',
                icon: 'none'
              });
            }}
          >
            <IconFont name="info" />
          </Cell>
          <Cell 
            title="清除缓存" 
            extra=""
            onClick={() => {
              Taro.showToast({
                title: '清除成功',
                icon: 'success'
              });
            }}
          >
            <IconFont name="delete" />
          </Cell>
        </Cell.Group>
      </View>
      
      <View className="logout-area">
        <Button 
          block 
          className="logout-button"
          onClick={handleLogout}
        >
          退出登录
        </Button>
      </View>
      
      <Toast
        visible={showToast}
        content={toastMessage}
        onClose={() => setShowToast(false)}
        type="warn"
        duration={2000}
      />
    </View>
  );
};

export default Profile; 